package com.itboye.mengwu.main;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.expandablelistview.BaseSwipeMenuExpandableListAdapter;
import com.allen.expandablelistview.SwipeMenuExpandableCreator;
import com.allen.expandablelistview.SwipeMenuExpandableListView;
import com.allen.expandablelistview.SwipeMenuExpandableListView.OnMenuItemClickListenerForExpandable;
import com.baoyz.swipemenulistview.ContentViewWrapper;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ParseDouble;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.login.ui.LoginActivity;
import com.itboye.mengwu.app.ui.main.GoodsDetailActivity;
import com.itboye.mengwu.buy.ui.QueRenDingDanNew;
import com.itboye.mengwu.data.model.ShopCarBean;
import com.itboye.mengwu.data.model.ShopCarBeanCopy;
import com.itboye.mengwu.data.model.ShopCarBeanCopy.StoreList;
import com.itboye.mengwu.data.model.ShopCarBeanCopy.StoreList.Cart;
import com.itboye.mengwu.data.presenter.ShopCarPresenter;
import com.jock.adapter.ShopcartExpandableListViewAdapter;
import com.jock.adapter.ShopcartExpandableListViewAdapter.CheckInterface;
import com.jock.adapter.ShopcartExpandableListViewAdapter.ModifyCountInterface;

public class FragmentShopcart extends BaseFragment implements CheckInterface,
		ModifyCountInterface, OnClickListener, Observer {
	private SwipeMenuExpandableListView exListView;
	// private CheckBox cb_check_all;
	private TextView tv_total_price;
	private TextView tv_delete;
	private TextView tv_go_to_pay;
	private Context context;
	private ShopCarBeanCopy dataList;
	private double totalPrice = 0.00;// 购买的商品总价
	private int totalCount = 0;// 购买的商品总数量
	ImageView back;
	private List<ApplicationInfo> mAppList = new ArrayList<ApplicationInfo>();
	TextView txt_title;
	private ShopcartExpandableListViewAdapter selva;
	// private List<GroupInfo> groups = new ArrayList<GroupInfo>();// 组元素数据列表
	protected String uid = "";
	ShopCarPresenter carPresenter;
	LinearLayout bottom;
//	RefreshLayout refresh;
	public static String changeCart = "changeshopcart";
	TextView guang;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_shopcart;
	}

	@Override
	public void onMyActivityCreated() {
		// TODO Auto-generated method stub
		mAppList = getActivity().getPackageManager()
				.getInstalledApplications(0);
		uid = (String) SPUtils.get(getContext(), null, SpPublicParams.UID, "");
		if (uid == "" || uid == null) {
			setInvisible();
		} else {
			setVisible();
		}
		IntentFilter filter = new IntentFilter(changeCart);
		getActivity().registerReceiver(broadcastReceiver, filter);
		carPresenter = new ShopCarPresenter(this);
		if (uid == "" || uid == null) {

		} else
			carPresenter.getShopcar(uid);
		initView2();
		back.setVisibility(View.GONE);
		txt_title.setVisibility(View.VISIBLE);
		txt_title.setText("购物车");
		// 加载监听器
		// refresh.setRefreshing(true);
		// refresh.set
		// refresh.setLoading(true);
//		refresh.setOnLoadListener(new OnLoadListener() {
//
//			@Override
//			public void onLoad() {
//
//				Toast.makeText(getActivity(), "load", Toast.LENGTH_SHORT)
//						.show();
//
//				refresh.postDelayed(new Runnable() {
//
//					@Override
//					public void run() {
//						// 加载完后调用该方法
//						refresh.setLoading(false);
//					}
//				}, 1500);
//
//			}
//		});
//		refresh.setOnRefreshListener(new OnRefreshListener() {
//
//			@Override
//			public void onRefresh() {
//				// TODO Auto-generated method stub
//				refresh.postDelayed(new Runnable() {
//
//					@Override
//					public void run() {
//						// 加载完后调用该方法
//						refresh.setRefreshing(false);
//					}
//				}, 1500);
//			}
//		});
		exListView.setMenuCreator(creator);
		exListView
				.setOnMenuItemClickListener(new OnMenuItemClickListenerForExpandable() {

					@Override
					public boolean onMenuItemClick(int groupPosition,
							int childPosition, SwipeMenu menu, int index) {
						// TODO Auto-generated method stub
						// ByAlert.alert("groupPosition" + groupPosition
						// + "childPosition" + childPosition);
						ShopCarBean model = new ShopCarBean();
						model.setUid(uid);
						model.setId(dataList.getStoreList().get(groupPosition)
								.getCarts().get(childPosition).getId());
						carPresenter.delete(model);
						return true;
					}
				});
		guang.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent("set");
				intent.putExtra("index", 0);
				getActivity().sendBroadcast(intent);
			}
		});
		exListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						GoodsDetailActivity.class);
				intent.putExtra("pid",
						dataList.getStoreList().get(groupPosition).getCarts()
								.get(childPosition).getPId());
				startActivity(intent);
				return true;
			}
		});
	}

	public void setInvisible() {
		getView().findViewById(R.id.btn_login).setVisibility(View.VISIBLE);
		getView().findViewById(R.id.btn_login).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(getActivity(),
								LoginActivity.class));
					}
				});
		getView().findViewById(R.id.totop).setVisibility(View.GONE);
		exListView.setVisibility(View.GONE);
		getView().findViewById(R.id.bottom).setVisibility(View.GONE);
	}

	public void setVisible() {
		getView().findViewById(R.id.btn_login).setVisibility(View.GONE);
		// getView().findViewById(R.id.delete).setVisibility(View.VISIBLE);
		// getView().findViewById(R.id.selectedAll).setVisibility(View.VISIBLE);
		exListView.setVisibility(View.VISIBLE);
		getView().findViewById(R.id.bottom).setVisibility(View.VISIBLE);
	}

	SwipeMenuExpandableCreator creator = new SwipeMenuExpandableCreator() {
		@Override
		public void createGroup(SwipeMenu menu) {
			// Create different menus depending on the view type
//			SwipeMenuItem item2 = new SwipeMenuItem(getActivity());
//			item2.setBackground(new ColorDrawable(Color.rgb(0xFF, 0x6E, 0xA5)));
//			item2.setWidth(dp2px(90));
//			item2.setTitle("删除");
//			item2.setTitleColor(R.color.white);
//			// item2.setIcon(R.drawable.ic_action_discard);
//			menu.addMenuItem(item2);
			// switch (menu.getViewType()) {
			// case 0:
			// createMenu1(menu);
			// break;
			// case 1:
			// createMenu2(menu);
			// break;
			// case 2:
			// createMenu3(menu);
			// break;
			// }
		}

		@Override
		public void createChild(SwipeMenu menu) {
			// Create different menus depending on the view type
			SwipeMenuItem item2 = new SwipeMenuItem(getActivity());
			item2.setBackground(new ColorDrawable(Color.rgb(0xff, 0x6e, 0xa5)));
			item2.setWidth(dp2px(90));
			item2.setTitle("删除");
			item2.setTitleSize(18);
			item2.setTitleColor(Color.parseColor("#ffffff"));
			// item2.setIcon(R.drawable.ic_action_discard);
			menu.addMenuItem(item2);
		}
	};

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		//
		@Override
		public void onReceive(Context context, Intent intent) {
			uid = (String) SPUtils.get(getContext(), null, SpPublicParams.UID,
					"");
			System.out.println("<><><>UIKD" + uid);
			if (!uid.equals("") && uid != null) {
				carPresenter.getShopcar(uid);
				setVisible();
			} else {
				setInvisible();
			}
		}
	};
	private AppAdapter mAdapter;

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	private void initView2() {
		context = getActivity();
		// virtualData();
		exListView = (SwipeMenuExpandableListView) getActivity().findViewById(
				R.id.exListView);
		// cb_check_all = (CheckBox)
		// getActivity().findViewById(R.id.all_chekbox);
		tv_total_price = (TextView) getActivity().findViewById(
				R.id.tv_total_price);
		tv_delete = (TextView) getActivity().findViewById(R.id.tv_delete);
		tv_go_to_pay = (TextView) getActivity().findViewById(R.id.tv_go_to_pay);
	}

	@SuppressWarnings("deprecation")
	private void initEvents() {
		mAdapter = new AppAdapter();
		exListView.setAdapter(mAdapter);
		mAdapter.setCheckInterface(this);// 关键步骤1,设置复选框接口
		mAdapter.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
		for (int i = 0; i < mAdapter.getGroupCount(); i++) {
			exListView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
		}
		calculate();
	}

	/**
	 * Basically, it's the same as BaseExpandableListAdapter. But added controls
	 * to every item's swipability
	 * 
	 * @author yuchentang
	 * @see android.widget.BaseExpandableListAdapter
	 */
	class AppAdapter extends BaseSwipeMenuExpandableListAdapter {
		CheckInterface checkInterface;
		ModifyCountInterface modifyCountInterface;
		ViewHolder holder = null;

		/**
		 * Whether this group item swipable
		 * 
		 * @param groupPosition
		 * @return
		 * @see com.allen.expandablelistview.BaseSwipeMenuExpandableListAdapter#isGroupSwipable(int)
		 */
		public void setCheckInterface(CheckInterface checkInterface) {
			this.checkInterface = checkInterface;
		}

		public void setModifyCountInterface(
				ModifyCountInterface modifyCountInterface) {
			this.modifyCountInterface = modifyCountInterface;
		}

		@Override
		public boolean isGroupSwipable(int groupPosition) {
			return true;
		}

		/**
		 * Whether this child item swipable
		 * 
		 * @param groupPosition
		 * @param childPosition
		 * @return
		 * @see com.allen.expandablelistview.BaseSwipeMenuExpandableListAdapter#isChildSwipable(int,
		 *      int)
		 */
		@Override
		public boolean isChildSwipable(int groupPosition, int childPosition) {
			return true;
		}

		@Override
		public int getChildType(int groupPosition, int childPosition) {
			return childPosition % 3;
		}

		@Override
		public int getChildTypeCount() {
			return 3;
		}

		@Override
		public int getGroupType(int groupPosition) {
			return groupPosition % 3;
		}

		@Override
		public int getGroupTypeCount() {
			return 3;
		}

		class ViewHolder {
			ImageView iv_icon;
			TextView tv_name, tv_intro, tv_price, tv_type_size, tv_num,
					tv_reduce, tv_add, tv_count;
			CheckBox cb_check, determine_chekbox;

			public ViewHolder(View view) {
				// iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
				tv_name = (TextView) view.findViewById(R.id.tv_source_name);
				determine_chekbox = (CheckBox) view
						.findViewById(R.id.determine_chekbox);
				view.setTag(this);
			}

			public ViewHolder(View view, int type) {
				iv_icon = (ImageView) view
						.findViewById(R.id.iv_adapter_list_pic);
				tv_name = (TextView) view.findViewById(R.id.tv_intro);
				tv_intro = (TextView) view.findViewById(R.id.tv_intro);
				tv_price = (TextView) view.findViewById(R.id.tv_price);
				tv_type_size = (TextView) view.findViewById(R.id.tv_type_size);
				tv_num = (TextView) view.findViewById(R.id.tv_num);
				cb_check = (CheckBox) view.findViewById(R.id.check_box);
				tv_reduce = (TextView) view.findViewById(R.id.tv_reduce);
				tv_add = (TextView) view.findViewById(R.id.tv_add);
				tv_count = (TextView) view.findViewById(R.id.tv_num);
				view.setTag(this);
			}
		}

		@Override
		public int getGroupCount() {
			return dataList.getStoreList().size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return dataList.getStoreList().get(groupPosition).getCarts().size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return dataList.getStoreList().get(groupPosition);
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			Cart childs = dataList.getStoreList().get(groupPosition).getCarts()
					.get(childPosition);
			return childs;
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public ContentViewWrapper getGroupViewAndReUsable(
				final int groupPosition, boolean isExpanded, View convertView,
				ViewGroup parent) {
			boolean reUseable = true;
			if (convertView == null) {
				convertView = View.inflate(context,
						R.layout.item_shopcart_group, null);
				convertView.setTag(new ViewHolder(convertView));
				reUseable = false;
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
			holder.tv_name.setText(dataList.getStoreList().get(groupPosition)
					.getName());
			holder.determine_chekbox.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v)

				{
					dataList.getStoreList().get(groupPosition)
							.setSelected(((CheckBox) v).isChecked());
					checkInterface.checkGroup(groupPosition,
							((CheckBox) v).isChecked());// 暴露组选接口
				}
			});
			holder.determine_chekbox.setChecked(dataList.getStoreList()
					.get(groupPosition).isSelected());
			return new ContentViewWrapper(convertView, reUseable);
		}

		@Override
		public ContentViewWrapper getChildViewAndReUsable(
				final int groupPosition, final int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			boolean reUseable = true;
			if (convertView == null) {
				convertView = View.inflate(context,
						R.layout.item_shopcart_product, null);
				convertView.setTag(new ViewHolder(convertView, 0));
				reUseable = false;
			}
			holder = (ViewHolder) convertView.getTag();
			if (null == holder) {
				holder = new ViewHolder(convertView, 0);
			}

			convertView.setBackgroundColor(Color.GRAY);
			XImageLoader.load(GlobalConfig.API_URL
					+ "/picture/index?id="
					+ dataList.getStoreList().get(groupPosition).getCarts()
							.get(childPosition).getIconUrl(), holder.iv_icon);
			holder.tv_name.setText(dataList.getStoreList().get(groupPosition)
					.getCarts().get(childPosition).getName());
			holder.tv_price.setText("￥"
					+ dataList.getStoreList().get(groupPosition).getCarts()
							.get(childPosition).getPrice() + "");
			holder.tv_num.setText(dataList.getStoreList().get(groupPosition)
					.getCarts().get(childPosition).getCount()
					+ "");
			holder.cb_check.setChecked(dataList.getStoreList()
					.get(groupPosition).getCarts().get(childPosition)
					.isSelected());
			holder.cb_check.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dataList.getStoreList().get(groupPosition).getCarts()
							.get(childPosition)
							.setSelected(((CheckBox) v).isChecked());
					holder.cb_check.setChecked(((CheckBox) v).isChecked());
					checkInterface.checkChild(groupPosition, childPosition,
							((CheckBox) v).isChecked());// 暴露子选接口
				}
			});
			holder.tv_add.setTag(dataList.getStoreList().get(groupPosition)
					.getCarts().get(childPosition).getId());
			holder.tv_add.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					modifyCountInterface.doIncrease(groupPosition,
							childPosition, holder.tv_count,
							holder.cb_check.isChecked(), v.getTag() + "");// 暴露增加接口
				}
			});
			holder.tv_reduce.setTag(dataList.getStoreList().get(groupPosition)
					.getCarts().get(childPosition).getId());
			holder.tv_reduce.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					modifyCountInterface.doDecrease(groupPosition,
							childPosition, holder.tv_count,
							holder.cb_check.isChecked(), v.getTag() + "");// 暴露删减接口
				}
			});
			// holder.tv_name.setText("this is child");
			return new ContentViewWrapper(convertView, reUseable);
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
	}

	/**
	 * 模拟数据<br>
	 * 遵循适配器的数据列表填充原则，组元素被放在一个List中，对应的组元素下辖的子元素被放在Map中，<br>
	 * 其键是组元素的Id(通常是一个唯一指定组元素身份的值)
	 */
	// private void virtualData()
	// {
	//
	// for (int i = 0; i < dataList.size(); i++)
	// {
	//
	// groups.add(new GroupInfo(i + "", "第八号当铺" + (i + 1) + "号店"));
	//
	// List<ProductInfo> products = new ArrayList<ProductInfo>();
	// for (int j = 0; j <= i; j++)
	// {
	//
	// products.add(new ProductInfo(j + "", "商品", "", groups.get(i).getName() +
	// "的第" + (j + 1) + "个商品", 120.00 + i * j, 1));
	// }
	// children.put(groups.get(i).getId(), products);//
	// 将组元素的一个唯一值，这里取Id，作为子元素List的Key
	// }
	// }

	ArrayList<String> idsArray = new ArrayList<>();

	@Override
	public void onClick(View v) {
		AlertDialog alert;
		switch (v.getId()) {
		// case R.id.all_chekbox:
		// doCheckAll();
		// break;
		case R.id.tv_go_to_pay:
			if (totalCount == 0) {
				Toast.makeText(context, "请选择要支付的商品", Toast.LENGTH_LONG).show();
				return;
			}
			alert = new AlertDialog.Builder(context).create();
			alert.setTitle("操作提示");
			alert.setMessage("总计:\n" + totalCount + "种商品\n"
					+ ParseDouble.getDouble(totalPrice) + "元");
			alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});
			alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							ArrayList<StoreList> arrayGroup = new ArrayList<StoreList>();
							for (int i = 0; i < dataList.getStoreList().size(); i++) {
								if (dataList.getStoreList().get(i).isSelected()) {
									arrayGroup.add(dataList.getStoreList().get(
											i));
								} else {
									for (int j = 0; j < dataList.getStoreList()
											.get(i).getCarts().size(); j++) {
										if (dataList.getStoreList().get(i)
												.getCarts().get(j).isSelected()) {
											arrayGroup.add(dataList
													.getStoreList().get(i));
											j = dataList.getStoreList().get(i)
													.getCarts().size();
										}
									}
								}
							}
							Intent intent = new Intent(getActivity(),
									QueRenDingDanNew.class);

							intent.putExtra("price", totalPrice + "");
							intent.putExtra("list", arrayGroup);
							startActivity(intent);
							return;
						}
					});
			alert.show();
			break;
		case R.id.tv_delete:
			if (totalCount == 0) {
				Toast.makeText(context, "请选择要移除的商品", Toast.LENGTH_LONG).show();
				return;
			}
			alert = new AlertDialog.Builder(context).create();
			alert.setTitle("操作提示");
			alert.setMessage("您确定要将这些商品从购物车中移除吗？");
			alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});
			alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							doDelete();
						}
					});
			alert.show();
			break;
		}
	}

	/**
	 * 删除操作<br>
	 * 1.不要边遍历边删除，容易出现数组越界的情况<br>
	 * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除
	 */
	StringBuffer ids = new StringBuffer();
	private int currentCountTemp;
	private int groupPosition;
	private int childPosition;
	private String id;

	protected void doDelete() {
		if (ids.length() > 0) {

		}
		List<ShopCarBeanCopy.StoreList> toBeDeleteGroups = new ArrayList<ShopCarBeanCopy.StoreList>();//
		// 待删除的组元素列表
		for (int i = 0; i < dataList.getStoreList().size(); i++) {
			ShopCarBeanCopy.StoreList group = dataList.getStoreList().get(i);
			if (group.isSelected()) {
				toBeDeleteGroups.add(group);
			}
			List<ShopCarBeanCopy.StoreList.Cart> toBeDeleteProducts = new ArrayList<ShopCarBeanCopy.StoreList.Cart>();// 待删除的子元素列表
			for (int j = 0; j < dataList.getStoreList().get(i).getCarts()
					.size(); j++) {
				if (dataList.getStoreList().get(i).getCarts().get(j)
						.isSelected()) {
					toBeDeleteProducts.add(dataList.getStoreList().get(i)
							.getCarts().get(j));
					ids.append(dataList.getStoreList().get(i).getCarts().get(j)
							.getId()
							+ ",");
				}
			}
			// dataList.get(i).getCarts().removeAll(toBeDeleteProducts);//删除商品

		}
		//
		// dataList.getStoreList().removeAll(toBeDeleteGroups);// 删除组元素
		ShopCarBean model = new ShopCarBean();
		model.setUid(uid);
		model.setId(ids.substring(0, ids.length() - 1));
		carPresenter.delete(model);
	}

	@Override
	public void doIncrease(int groupPosition, int childPosition,
			View showCountView, boolean isChecked, String id) {
		ShopCarBeanCopy.StoreList.Cart product = (ShopCarBeanCopy.StoreList.Cart) mAdapter
				.getChild(groupPosition, childPosition);
		int currentCount = Integer.parseInt(product.getCount());
		currentCount++;
		currentCountTemp = currentCount;

		this.groupPosition = groupPosition;
		this.childPosition = childPosition;
		this.id = dataList.getStoreList().get(groupPosition).getCarts()
				.get(childPosition).getId();
		ShopCarBean model = new ShopCarBean();
		model.setUid(uid);
		model.setId(dataList.getStoreList().get(groupPosition).getCarts()
				.get(childPosition).getId());
		model.setCount(currentCount + "");
		carPresenter.update(model);
	}

	@Override
	public void doDecrease(int groupPosition, int childPosition,
			View showCountView, boolean isChecked, String id) {
		// ByAlert.alert("id"+dataList.getStoreList().get(groupPosition).getCarts().get(childPosition).getId());
		ShopCarBeanCopy.StoreList.Cart product = (ShopCarBeanCopy.StoreList.Cart) mAdapter
				.getChild(groupPosition, childPosition);
		int currentCount = Integer.parseInt(product.getCount());
		if (currentCount == 1)
			return;
		currentCount--;
		currentCountTemp = currentCount;
		this.groupPosition = groupPosition;
		this.childPosition = childPosition;
		this.id = dataList.getStoreList().get(groupPosition).getCarts()
				.get(childPosition).getId();
		ShopCarBean model = new ShopCarBean();
		model.setUid(uid);
		model.setId(dataList.getStoreList().get(groupPosition).getCarts()
				.get(childPosition).getId());
		model.setCount(currentCount + "");
		carPresenter.update(model);
	}

	@Override
	public void checkGroup(int groupPosition, boolean isChecked) {
		ShopCarBeanCopy.StoreList group = dataList.getStoreList().get(
				groupPosition);
		for (int i = 0; i < group.getCarts().size(); i++) {
			group.getCarts().get(i).setSelected(isChecked);
		}
		// if (isAllCheck())
		// cb_check_all.setChecked(true);
		// else
		// cb_check_all.setChecked(false);
		mAdapter.notifyDataSetChanged();
		calculate();
	}

	@Override
	public void checkChild(int groupPosition, int childPosiTion,
			boolean isChecked) {
		boolean allChildSameState = true;// 判断改组下面的所有子元素是否是同一种状态
		ShopCarBeanCopy.StoreList group = dataList.getStoreList().get(
				groupPosition);
		for (int i = 0; i < group.getCarts().size(); i++) {
			if (group.getCarts().get(i).isSelected() != isChecked) {
				allChildSameState = false;
				break;
			}
		}
		if (allChildSameState) {
			group.setSelected(isChecked);// 如果所有子元素状态相同，那么对应的组元素被设为这种统一状态
		} else {
			group.setSelected(false);// 否则，组元素一律设置为未选中状态
		}

		// if (isAllCheck())
		// cb_check_all.setChecked(true);
		// else
		// cb_check_all.setChecked(false);
		mAdapter.notifyDataSetChanged();
		calculate();
	}

	private boolean isAllCheck() {

		for (ShopCarBeanCopy.StoreList group : dataList.getStoreList()) {
			if (!group.isSelected())
				return false;

		}

		return true;
	}

	// /** 全选与反选 */
	// private void doCheckAll() {
	// for (int i = 0; i < dataList.getStoreList().size(); i++) {
	// dataList.getStoreList().get(i)
	// .setSelected(cb_check_all.isChecked());
	// ShopCarBeanCopy.StoreList group = dataList.getStoreList().get(i);
	// for (int j = 0; j < group.getCarts().size(); j++) {
	// group.getCarts().get(j).setSelected(cb_check_all.isChecked());
	// }
	// }
	// mAdapter.notifyDataSetChanged();
	// }

	/**
	 * 统计操作<br>
	 * 1.先清空全局计数器<br>
	 * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
	 * 3.给底部的textView进行数据填充
	 */
	private void calculate() {
		totalCount = 0;
		totalPrice = 0.00;
		for (int i = 0; i < dataList.getStoreList().size(); i++) {
			for (int j = 0; j < dataList.getStoreList().get(i).getCarts()
					.size(); j++) {
				ShopCarBeanCopy.StoreList.Cart product = dataList
						.getStoreList().get(i).getCarts().get(j);
				if (product.isSelected()) {
					totalCount++;
					totalPrice += Float.parseFloat(product.getPrice())
							* Integer.parseInt(product.getCount());
				}
			}
		}
		tv_total_price.setText("￥" + ParseDouble.getDouble(totalPrice));
		tv_go_to_pay.setText("去支付(" + totalCount + ")");
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity.getEventType() == ShopCarPresenter.GoodsQueryALL_success) {
			dataList = (ShopCarBeanCopy) entity.getData();

			initEvents();
			if (dataList == null
					|| dataList.getStoreList().toString().equals("[]")) {
				System.out.println("dataList.getStoreList()"
						+ dataList.getStoreList());

				bottom.setVisibility(View.GONE);
				// getView().findViewById(R.id.selectedAll).setVisibility(
				// View.GONE);
				getView().findViewById(R.id.totop).setVisibility(View.VISIBLE);
			} else {
				if (dataList.getStoreList().size() <= 0) {
					bottom.setVisibility(View.GONE);
					// getView().findViewById(R.id.selectedAll).setVisibility(
					// View.GONE);
					getView().findViewById(R.id.totop).setVisibility(
							View.VISIBLE);
				} else {
					bottom.setVisibility(View.VISIBLE);
					// getView().findViewById(R.id.selectedAll).setVisibility(
					// View.VISIBLE);
					getView().findViewById(R.id.totop).setVisibility(View.GONE);
				}
			}
		} else if (entity.getEventType() == ShopCarPresenter.ShopCarFailEvent) {
			bottom.setVisibility(View.GONE);
			ByAlert.alert("购物车暂时没有东西");
		} else if (entity.getEventType() == ShopCarPresenter.ShopCarDelete_success) {
			ByAlert.alert(entity.getData() + "");
			carPresenter.getShopcar(uid);
			if (dataList.getStoreList().size() == 0) {
				bottom.setVisibility(View.GONE);
			} else {
				bottom.setVisibility(View.VISIBLE);
			}
		} else if (entity.getEventType() == ShopCarPresenter.ShopCarDeleteFailEvent) {
			ByAlert.alert("删除失败");
		} else if (entity.getEventType() == ShopCarPresenter.ShopCarUpdate_success) {
			// carPresenter.getShopcar(uid);
			try {
				Iterator<Cart> iterable = dataList.getStoreList()
						.get(groupPosition).getCarts().iterator();
				while (iterable.hasNext()) {
					System.out.println("shopcartId"
							+ dataList.getStoreList().get(groupPosition)
									.getCarts().get(childPosition).getId()
							+ "idididi" + id);
					if (dataList.getStoreList().get(groupPosition).getCarts()
							.get(childPosition).getId().equals(id)) {
						dataList.getStoreList().get(groupPosition).getCarts()
								.get(childPosition)
								.setCount(currentCountTemp + "");
						break;
					}

				}
				mAdapter.notifyDataSetChanged();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

			ByAlert.alert(entity.getData() + "");
			calculate();
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
